//
//  IGTopicDetailVC.m
//  jingdongfang
//
//  Created by BOE on 2017/8/22.
//  Copyright © 2017年 LJL. All rights reserved.
//

#import "IGTopicDetailVC.h"
#import "YXScrollowActionSheet.h"
#import "IGTopicDetailCommentCell.h"
#import "IGTopicDetailApi.h"
#import "IGCommunityPageApi.h"
#import "IGTopicCommentTableViewCell.h"
#import "IGTopicHeaderCell.h"
#import "IGTopicContentCell.h"
#import "IGTopicVideoCell.h"
#import "LJZFPlayerView.h"
#import "IGTopicImageCell.h"
#import "IGArtCardCell.h"
#import "IGTopicBottomCell.h"
#import "IGReportVC.h"
#import "IGReportTypeApi.h"
#import "IGCommonApi.h"
#import "IGEmptyView.h"
#import "ChatKeyBoard.h"
#import "IGCommentApi.h"
#import "IGArtGalleryAttentApi.h"

@interface IGTopicDetailVC ()<ChatKeyBoardDelegate, ChatKeyBoardDataSource, UITableViewDelegate, UITableViewDataSource, DZNEmptyDataSetSource, DZNEmptyDataSetDelegate, LJZFPlayerDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, copy) NSString *lastTimeDate;
@property (nonatomic, strong) IGTopicDetailApi *topicDetailApi;
@property (nonatomic, strong) IGTopicModel *topicModel;
@property (nonatomic, strong) IGCommentBean *replayCommentCellModel;
@property (nonatomic, strong) NSMutableArray *comments;
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, weak) LJZFPlayerView *playerView;
@property (nonatomic, strong) ChatKeyBoard *chatKeyBoard;
@property (nonatomic, strong) IGCommentApi *commentApi;

@end

@implementation IGTopicDetailVC

- (instancetype)initWithTopicId:(NSString *)topicId
{
    self = [super init];
    if (self) {
        _lastTimeDate = @"";
        _page = 1;
        self.topicDetailApi = [[IGTopicDetailApi alloc] initWithTopicId:topicId lastTimeDate:_lastTimeDate];
        self.topicDetailApi.page = self.page;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = NSLocalizedString(@"Topic Details", nil);
    self.view.backgroundColor = [UIColor mainBackgroundColor];
    AdjustsScrollViewInsetNever(self, self.tableView);
    
    [self ig_setupRightButtonItemWithTitle:@"" image:[UIImage imageNamed:@"share_parent"] highLightedImage:[UIImage imageNamed:@"share_parent"]];
    
    self.commentApi = [[IGCommentApi alloc] init];
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(0);
        make.top.mas_equalTo(NavigationMagin);
    }];
    __weak typeof(self) weakSelf = self;
    [self.tableView ig_setHeaderWithRefreshingBlock:^{
        weakSelf.lastTimeDate = @"";
        weakSelf.page = 1;
        weakSelf.topicDetailApi.lastTimeDate = weakSelf.lastTimeDate;
        weakSelf.topicDetailApi.page = weakSelf.page;
        
        [weakSelf requestData];
    }];
    
    [self requestData];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if (self.topicModel.feedType == FeedTypeMovie && !self.playerView.isPauseByUser && self.playerView.videoNetStatusing == LJVideoNetStatusNormal) {
        [self.playerView.player play];
    }
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    if (self.topicModel.feedType == FeedTypeMovie && !self.playerView.isPauseByUser) {
        [self.playerView.player pause];
    }
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    self.tableView = nil;
    if (self.topicModel.feedType == FeedTypeMovie) {
        [self.playerView pause];
        self.playerView = nil;
    }
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.emptyDataSetSource = self;
        _tableView.emptyDataSetDelegate = self;
        
        if (@available(iOS 11.0, *)) {
            _tableView.estimatedRowHeight = 0;
            _tableView.estimatedSectionHeaderHeight = 0;
            _tableView.estimatedSectionFooterHeight = 0;
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = [UIColor mainBackgroundColor];
    }
    return _tableView;
}

- (void)requestData {
    __weak typeof(self) weakSelf = self;
    [self.topicDetailApi startWithDecodeClass:[IGTopicDetailResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
        [weakSelf.tableView ig_endHeaderRefreshing];
        [weakSelf.tableView ig_endFooterRefreshing];
        
        if (responseObject) {
            IGTopicDetailResp *resp = responseObject;
            IGTopicDetailModel *model = resp.data;
            IGTopicModel *topicModel = model.topic;
            
            NSMutableArray *tmpTopicCom = topicModel.lstComments;
            if (tmpTopicCom && tmpTopicCom.count > 0) {
                [weakSelf setupFooter];
            } else {
                [weakSelf.tableView ig_endFooterRefreshingWithNoMoreData];
            }
            
            if (weakSelf.page == 1) {
                weakSelf.topicModel = topicModel;
            } else {
                [weakSelf.topicModel.lstComments addObjectsFromArray:tmpTopicCom];
            }
            
            if (weakSelf.topicModel.feedType == FeedTypeMovie) {
                [weakSelf.topicModel calVideoScreenRatioAndMovieUrl];
            }
            
            weakSelf.comments = weakSelf.topicModel.lstComments;
            weakSelf.lastTimeDate = model.commentTime;
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf.tableView reloadData];
            });
        } else {
            [weakSelf.navigationController popViewControllerAnimated:YES];
        }
    }];
}

- (void)setupFooter {
    __weak typeof(self) weakSelf = self;
    [self.tableView ig_setFooterWithRefreshingBlock:^{
        weakSelf.page++;
        weakSelf.topicDetailApi.lastTimeDate = weakSelf.lastTimeDate;
        weakSelf.topicDetailApi.page = weakSelf.page;
        
        [weakSelf requestData];
    }];
}

- (ChatKeyBoard *)chatKeyBoard {
    if (_chatKeyBoard == nil) {
        _chatKeyBoard = [ChatKeyBoard keyBoardWithNavgationBarTranslucent:YES];
        _chatKeyBoard.delegate = self;
        _chatKeyBoard.dataSource = self;
        _chatKeyBoard.keyBoardStyle = KeyBoardStyleComment;
        _chatKeyBoard.allowVoice = NO;
        _chatKeyBoard.allowMore = NO;
        _chatKeyBoard.allowFace = NO;
        _chatKeyBoard.allowSwitchBar = NO;
        _chatKeyBoard.placeHolder = NSLocalizedString(@"comment", nil);
        [self.view addSubview:_chatKeyBoard];
        [self.view bringSubviewToFront:_chatKeyBoard];
    }
    return _chatKeyBoard;
}

- (void)attention:(IGTopicModel *)model {
    if ([model.userId isEqualToString:[IGUser getUid]]) {
        [self presentMessageTips:@"你不能关注你自己!"];
        [self.tableView reloadData];
        return;
    }
    __weak typeof(self) weakSelf = self;
    IGArtGalleryAttentApi *attentApi = [IGArtGalleryAttentApi new];
    attentApi.museumId = model.userId;
    attentApi.operatorType = [model.isCollection boolValue]?@"1":@"0";
    [attentApi startWithDecodeClass:[IGArtGalleryAttentResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
        if (responseObject) {
            if ([model.isCollection boolValue]) {
                model.isCollection = @"0";
            } else {
                model.isCollection = @"1";
            }
        } else {
            if ([model.isCollection boolValue]) {
                [self presentMessageTips:NSLocalizedString(@"Follow Failed", nil)];
            } else {
                [self presentMessageTips:NSLocalizedString(@"Cancel Failed", nil)];
            }
        }
        [weakSelf.tableView reloadData];
    }];
}

- (void)ig_rightButtonPressed:(id)sender {
    __weak typeof(self) weakSelf = self;
    YXScrollowActionSheet *cusSheet = [[YXScrollowActionSheet alloc] init];
    NoParaNoReturnBlock reportBlock = ^() {
        [weakSelf reportRequest:weakSelf.topicModel];
    };
    NoParaNoReturnBlock delBlock = ^() {
        [UIAlertView bk_showAlertViewWithTitle:NSLocalizedString(@"Notice", nil) message:NSLocalizedString(@"Confirm to delete this topic?",nil) cancelButtonTitle:NSLocalizedString(@"Cancel", nil) otherButtonTitles:@[NSLocalizedString(@"Confirm", nil)] handler:^(UIAlertView *alertView, NSInteger buttonIndex) {
            if (buttonIndex == 1) {
                [weakSelf delTopicRequest];
            }
        }];
        
    };
    
    NSArray *contentArray = nil;
    NSArray *blockArray = nil;
    if ([[IGUser getUid] isEqualToString:weakSelf.topicModel.userId]) {
        contentArray = @[NSLocalizedString(@"Report", nil), NSLocalizedString(@"Delete", nil)];
        blockArray = @[reportBlock, delBlock];
    } else {
        contentArray = @[NSLocalizedString(@"Report", nil)];
        blockArray = @[reportBlock];
    }
    
    IGShareModel *shareModel = [weakSelf.topicModel getShareModel];
    cusSheet.shareModel = shareModel;
    [cusSheet showWithContentArray:contentArray blockArr:blockArray];
}

#pragma mark -UITableViewDelegate, UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.topicModel?2:0;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 5;
    } else if (section == 1) {
        return self.comments.count;
    }
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            return kTopicHeaderCellHeight;
        } else if (indexPath.row == 1) {
            return [IGTopicContentCell feedContentHeight:_topicModel];//内容
        } else if (indexPath.row == 2) {
            CGFloat cellHeight = 0;
            if (_topicModel.feedType == FeedTypeMovie) {
                cellHeight = [IGTopicVideoCell cellHeight:_topicModel];
            } else if (_topicModel.feedType == FeedTypeImage) {
                cellHeight = [IGTopicImageCell cellHeight:_topicModel];
            }
            return cellHeight;//图片或者视频
        } else if (indexPath.row == 3) {//关联的作品
            if ([_topicModel containProduct]) {
                return [IGArtCardCell cellHeight];
            } else {
                return 0;
            }
        } else if (indexPath.row == 4) {
            return [IGTopicBottomCell cellHeight];
        }
    } else if (indexPath.section == 1) {//评论栏
        IGCommentBean *model = [self.comments objectAtIndex:indexPath.row];
        CGFloat cell_height = [IGTopicDetailCommentCell hyb_heightForTableView:self.tableView config:^(UITableViewCell *sourceCell) {
            IGTopicDetailCommentCell *cell = (IGTopicDetailCommentCell *)sourceCell;
            [cell configCellWithModel:model];
        } cache:^NSDictionary *{
            NSDictionary *cache = @{kHYBCacheUniqueKey : [NSString stringWithFormat:@"k%@", model.commentId],
                                    kHYBCacheStateKey : @"",
                                    kHYBRecalculateForStateKey : @(YES)};
            model.shouldUpdateCache = NO;
            return cache;
        }];
        cell_height += 15;
        return cell_height;
    }
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return 15.0f;
    }
    return 44.0f;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section == 1 && self.comments.count > 0) {
        UIView *layerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KSCREENWIDTH, 44)];
        layerView.backgroundColor = [UIColor c3Color];
        
        UIImageView *imgView = [[UIImageView alloc] init];
        [layerView addSubview:imgView];
        [imgView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(15);
            make.top.mas_equalTo(13);
            make.width.height.mas_equalTo(18);
        }];
        
        UILabel *label = [UILabel new];
        label.textColor = [UIColor c4Color];
        label.font = [UIFont font18];
        [layerView addSubview:label];
        
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(imgView.mas_right).offset(10);
            make.top.bottom.mas_equalTo(0);
            make.width.mas_equalTo(200);
        }];
        
        UIView *lineView = [[UIView alloc] init];
        lineView.backgroundColor = [UIColor c2Color];
        [layerView addSubview:lineView];
        [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.mas_equalTo(0);
            make.height.mas_equalTo(1);
        }];
        
        label.text = NSLocalizedString(@"Comments", nil);
        imgView.image = [UIImage imageNamed:@"community_topic"];
        
        return layerView;
    }
    return nil;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    __weak typeof(self) weakSelf = self;
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            IGTopicHeaderCell *cell = [IGTopicHeaderCell cellWithTableView:tableView];
            cell.topicModel = _topicModel;
            cell.focusUser = ^{
                [weakSelf attention:weakSelf.topicModel];
            };
            return cell;
        } else if (indexPath.row == 1) {
            IGTopicContentCell *cell = [IGTopicContentCell cellWithTableView:tableView];
            cell.feedDetail = _topicModel;
            return cell;
        } else if (indexPath.row == 2) {
            if (_topicModel.feedType == FeedTypeMovie) {
                IGTopicVideoCell *cell = [IGTopicVideoCell cellWithTableView:tableView];
                cell.tableView = self.tableView;
                [cell loadCellWithDetail:_topicModel images:_topicModel.imgs];
                self.playerView = cell.playerView;
                self.playerView.delegate = self;
                self.playerView.fullScreenBlock = ^(BOOL isFullScreen) {
                    [[UIApplication sharedApplication] setStatusBarHidden:isFullScreen];
                };
                return cell;
            } else if (_topicModel.feedType == FeedTypeImage) {
                IGTopicImageCell *cell = [IGTopicImageCell cellWithTableView:tableView];
                cell.feedDetail = _topicModel;
                return cell;
            } else {
                UITableViewCell *cell = [[UITableViewCell alloc] init];
                return cell;
            }
        } else if (indexPath.row == 3) {
            if ([_topicModel containProduct]) {
                IGArtCardCell *cell = [IGArtCardCell cellWithTableView:tableView];
                cell.feedDetail = _topicModel;
                return cell;
            } else {
                UITableViewCell *cell = [[UITableViewCell alloc] init];
                return cell;
            }
        } else if (indexPath.row == 4) {
            IGTopicBottomCell *cell = [IGTopicBottomCell cellWithTableView:tableView];
            cell.topicModel = _topicModel;
            cell.likeBlock = ^{
                [weakSelf likeTopic:weakSelf.topicModel request:^() {
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"kTopicListRefresh" object:NSStringFromClass([weakSelf class])];
                    if (weakSelf.topicModel.isZan) {
                        weakSelf.topicModel.zanNums = [NSString stringWithFormat:@"%d", ([weakSelf.topicModel.zanNums intValue] - 1)];
                    } else {
                        weakSelf.topicModel.zanNums = [NSString stringWithFormat:@"%d", ([weakSelf.topicModel.zanNums intValue] + 1)];
                    }
                    weakSelf.topicModel.isZan = !weakSelf.topicModel.isZan;
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [weakSelf.tableView reloadData];
                    });
                }];
            };
            return cell;
        }
    } else if (indexPath.section == 1) {
        IGTopicDetailCommentCell *cell = [IGTopicDetailCommentCell cellWithTableView:tableView];
        IGCommentBean *model = [self.comments objectAtIndex:indexPath.row];
        [cell configCellWithModel:model];
        return cell;
    }
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 0) {
        return;
    }
    IGCommentBean *commentModel = self.comments[indexPath.row];
    self.replayCommentCellModel = commentModel;
    [self.chatKeyBoard keyboardUpforComment];
    self.chatKeyBoard.placeHolder = [NSString stringWithFormat:@"%@ %@", NSLocalizedString(@"Reply", nil),commentModel.commentUserNick];
}

- (void)reportRequest:(IGTopicModel *)model {
    IGReportTypeApi *reportTypeApi = [[IGReportTypeApi alloc] init];
    [reportTypeApi startWithDecodeClass:[IGReportTypeResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
        if (responseObject) {
            IGReportTypeResp *resp = responseObject;
            IGReportTypeModel *type = resp.data;
            
            IGReportVC *reportVC = [[IGReportVC alloc] initWithReportType:type.reports];
            reportVC.pId = model.tid;
            [UIViewController ig_pushViewController:reportVC animated:YES];
        }
    }];
}

- (void)delTopicRequest {
    IGCommonApi *api = [[IGCommonApi alloc] initWithApiType:IGiGalleryApiTypeCircleTopicDel];
    api.topicId = self.topicModel.tid;
    __weak typeof(self) weakSelf = self;
    [api startWithDecodeClass:[IGCommonResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
        if (responseObject) {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"kTopicListRefresh" object:NSStringFromClass([weakSelf class])];
            [weakSelf presentMessageTips:NSLocalizedString(@"Deleted Successfully", nil)];
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf.navigationController popViewControllerAnimated:YES];
            });
        } else { //删除失败恢复数据源中的数据
            [weakSelf presentMessageTips:NSLocalizedString(@"Delete Failed", nil)];
        }
    }];
}

- (void)likeTopic:(IGTopicModel *)model request:(NoParaNoReturnBlock)block {
    IGCommonApi *api = [[IGCommonApi alloc] initWithApiType:IGiGalleryApiTypeCircleTopicLike];
    api.topicId = model.tid;
    [api startWithDecodeClass:[IGCommonResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
        if (responseObject) {
            if (block) {
                block();
            }
        }
    }];
}
# pragma mark - ChatKeyBoardDelegate
- (void)chatKeyBoardSendText:(NSString *)text{
    if ([text isEmpty]) {
        //        [self presentMessageTips:@"请输入评论内容"];
        [self presentMessageTips:NSLocalizedString(@"Add your comments", nil)];
        return;
    }
    
    IGCommentType commentType = IGCommentTypeFirst;
    if (self.replayCommentCellModel) {
        commentType = IGCommentTypeSecond;
    }
    
    [self.chatKeyBoard keyboardDownForComment];
    self.chatKeyBoard.placeHolder = nil;
    
    //提交数据==>若失败刷新界面
    self.commentApi.pid = _topicModel.tid;
    self.commentApi.parentType = IGParentTypeTopic;
    self.commentApi.content = text;
    self.commentApi.commentType = commentType;
    self.commentApi.opusId = _topicModel.product.artId;
    if (commentType == IGCommentTypeFirst) {
        self.commentApi.parentUid = _topicModel.userId;
        self.commentApi.cId = @"";
    } else {
        self.commentApi.parentUid = self.replayCommentCellModel.commentUserId;
        self.commentApi.cId = self.replayCommentCellModel.commentId;
    }
    
    [self commitCommentRequest];
}

- (void)commitCommentRequest {
    __weak typeof(self) weakSelf = self;
    [self.commentApi startWithDecodeClass:[IGCommentResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
        if (responseObject) {
            IGCommentResp *resp = responseObject;
            IGCommentModel *model = resp.data;
            IGCommentBean *commentModel = model.comment;
            
            weakSelf.topicModel.commentNums = [NSString stringWithFormat:@"%d", ([weakSelf.topicModel.commentNums intValue] + 1)];
            [weakSelf.comments insertObject:commentModel atIndex:0];
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf.tableView reloadData];
            });
        }
    }];
}
#pragma mark - ChatKeyBoardDataSource 这里面的评论只允许文字
- (NSArray<MoreItem *> *)chatKeyBoardMorePanelItems
{
    return nil;
}

- (NSArray<ChatToolBarItem *> *)chatKeyBoardToolbarItems
{
    return nil;
}

- (NSArray<FaceThemeModel *> *)chatKeyBoardFacePanelSubjectItems
{
    return nil;
}
#pragma mark -Empty
- (BOOL)emptyDataSetShouldDisplay:(UIScrollView *)scrollView {
    return YES;
}

- (BOOL)emptyDataSetShouldAllowTouch:(UIScrollView *)scrollView {
    return YES;
}

- (void)emptyDataSetDidTapView:(UIScrollView *)scrollView {
    [self requestData];
}

- (UIView *)customViewForEmptyDataSet:(UIScrollView *)scrollView {
    IGEmptyView *emptyView = [[IGEmptyView alloc] init];
    //    emptyView.title = @"暂无数据~";
    emptyView.title = NSLocalizedString(@"No Data", nil);
    emptyView.requestApi = self.topicDetailApi;
    return emptyView;
}
#pragma mark - 转屏相关

// 是否支持自动转屏
- (BOOL)shouldAutorotate
{
    return YES;
}

// 支持哪些转屏方向
- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
    if (self.topicModel.videoScreenRatio == VideoScreenRatioWBH && self.playerView.isFullScreen) {
        return UIInterfaceOrientationMaskAllButUpsideDown;
    } else {
        return UIInterfaceOrientationMaskPortrait;
    }
}

// 默认的屏幕方向（当前ViewController必须是通过模态出来的UIViewController（模态带导航的无效）方式展现出来的，才会调用这个方法）
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
    return UIInterfaceOrientationPortrait;
}

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
    if (toInterfaceOrientation == UIInterfaceOrientationPortrait) {
        self.view.backgroundColor = [UIColor whiteColor];
    }else if (toInterfaceOrientation == UIInterfaceOrientationLandscapeRight || toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft) {
        self.view.backgroundColor = [UIColor blackColor];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
